	package lifeOfAFish.scenegraph.geom;

import java.io.File;

import javax.media.opengl.*;

import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureIO;

import lifeOfAFish.scenegraph.*;
import lifeOfAFish.util.MeshLoader;

public class sgGeomRectXY extends sgGeometry {

	private float m_alpha = 1.0f;
	private float[] m_points = new float[4];
	private sgVec3 m_normal = null;
	private boolean m_created = false;
	private int m_displayList = -1;
	private float m_res = 20.0f;

	public sgGeomRectXY()
	{
	}
	
	public sgGeomRectXY(float[] p)
	{
		setPoints(p);
	}
	
	public sgGeomRectXY(float x1, float x2, float y1, float y2)
	{
		setPoints(x1, x2, y1, y2);
	}
	
	public void setRes(float r) {m_res = r;}
	
	public void setAlpha(float a)
	{
		m_alpha = a;
	}
	
	public void setNormal(sgVec3 n){
		m_normal = n;
	}
	
	public void setPoints(float[] p){
		for (int i = 0; i < p.length; i++)
		{
			m_points[i] = p[i];
		}
	}
	
	public void setPoints(float x1, float x2, float y1, float y2)
	{
		float[] p = {x1, x2, y1, y2};
		this.setPoints(p);
	}
	
	// additional push - texture bit
	protected void push()
	{
		super.push();
		sgGlobals.gl.glPushAttrib(GL.GL_TEXTURE_BIT);
	}
	
	// additional pop
	protected void pop()
	{
		super.pop();
		sgGlobals.gl.glPopAttrib();
	}
	
	/**
	 * Render the model, optional binding texture if necessary
	 */
	protected void draw()
	{
		GL gl = sgGlobals.gl;
		if(!m_created) create();
		this.bindTexture();
		gl.glCallList(m_displayList);
		this.unbindTexture();
	};
	
	
	private void create()
	{
		
		GL gl = sgGlobals.gl;
		
		m_displayList = gl.glGenLists(1);
		gl.glNewList(m_displayList, GL.GL_COMPILE);
		gl.glBegin(GL.GL_QUADS);	
		
			float x = m_points[0];
			float width = m_points[1]-m_points[0];
			float sx = width/m_res;
			for(;x < m_points[0]+width; x += sx){
				float y = m_points[2];
				float height = m_points[3]-m_points[2];
				float sy = height/m_res;
				for(;y < m_points[2]+height; y += sy){
					gl.glTexCoord2f(x/width, y/height); gl.glVertex3f(x, y, 0.0f);
					gl.glTexCoord2f((x+sx)/width, y/height); gl.glVertex3f(x+sx, y, 0.0f);
					gl.glTexCoord2f((x+sx)/width, (y+sy)/height); gl.glVertex3f(x+sx, y+sy, 0.0f);
					gl.glTexCoord2f((x)/width, (y+sy)/height); gl.glVertex3f(x, y+sy, 0.0f);
					
				}
			}
		
		gl.glEnd();	
		gl.glEndList();
		
		m_created = true;
	}
	
	/**
	 * Return (local) bounding box
	 */
	public float[] getBoundingBox(){
		

		float[] ret = {m_points[0], m_points[1], m_points[2], m_points[3], 0.0f, 0.0f};
		return ret;
		
	}

}
